
<template>
  <div class="market-table">
    <div class="overflow-x-auto">
      <table class="finance-table">
        <thead>
          <tr>
            <th v-for="column in columns" :key="column.dataIndex" :class="column.width ? column.width : ''">
              <div class="flex items-center">
                <span>{{ column.title }}</span>
                <button 
                  v-if="column.sorter" 
                  @click="handleSort(column.dataIndex)"
                  class="ml-1 text-slate-400 hover:text-white focus:outline-none"
                >
                  <i :class="getSortIcon(column.dataIndex)"></i>
                </button>
              </div>
            </th>
          </tr>
        </thead>
        
        <tbody>
          <template v-if="loading">
            <tr v-for="i in 10" :key="`loading-${i}`" class="animate-pulse">
              <td v-for="column in columns" :key="`loading-${column.dataIndex}`">
                <div class="h-4 bg-slate-700 rounded"></div>
              </td>
            </tr>
          </template>
          <template v-else-if="data.length === 0">
            <tr>
              <td :colspan="columns.length" class="text-center py-8 text-slate-500">
                <i class="fas fa-database mr-2"></i> 暂无数据
              </td>
            </tr>
          </template>
          <template v-else>
            <tr 
              v-for="record in paginatedData" 
              :key="record.key || record.rank" 
              class="hover:bg-slate-800"
              @click="handleRowClick(record)"
            >
              <td v-for="column in columns" :key="column.dataIndex">
                <template v-if="column.dataIndex === 'regionName'">
                  <a 
                    :href="record.region.url" 
                    target="_blank" 
                    class="text-finance-blue-400 hover:text-finance-blue-300"
                    @click.stop
                  >
                    {{ record.region.name }}
                  </a>
                </template>
                
                <template v-else-if="column.dataIndex === 'change'">
                  <span :class="record.change.isNegative ? 'text-fall' : 'text-rise'">
                    {{ record.change.value }}
                    <i :class="record.change.isNegative ? 'fas fa-caret-down ml-1' : 'fas fa-caret-up ml-1'"></i>
                  </span>
                </template>
                
                <template v-else-if="column.dataIndex === 'netflow'">
                  <span :class="parseFloat(record.netflow) >= 0 ? 'text-rise' : 'text-fall'">
                    {{ record.netflow }}
                    <i :class="parseFloat(record.netflow) >= 0 ? 'fas fa-caret-up ml-1' : 'fas fa-caret-down ml-1'"></i>
                  </span>
                </template>
                
                <template v-else-if="column.dataIndex === 'upCount'">
                  <span class="text-rise">{{ record.upCount }}</span>
                </template>
                
                <template v-else-if="column.dataIndex === 'downCount'">
                  <span class="text-fall">{{ record.downCount }}</span>
                </template>
                
                <template v-else-if="column.dataIndex === 'leadingStockName'">
                  <a 
                    :href="record.leadingStock.url" 
                    target="_blank" 
                    class="text-finance-blue-400 hover:text-finance-blue-300"
                    @click.stop
                  >
                    {{ record.leadingStock.name }}
                  </a>
                </template>
                
                <template v-else-if="column.dataIndex === 'latestPrice'">
                  <span class="text-rise">{{ record.leadingStock.latestPrice }}</span>
                </template>
                
                <template v-else-if="column.dataIndex === 'leadingStockChange'">
                  <span class="text-rise">{{ record.leadingStock.change }}</span>
                </template>
                
                <template v-else>
                  {{ getValueByPath(record, column.dataIndex) }}
                </template>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>
    <div class="px-4 py-3 flex items-center justify-between border-t border-slate-700">
      <div>
        <select 
          v-model="pageSize" 
          class="bg-slate-800 border border-slate-700 text-slate-300 text-sm rounded block p-1"
        >
          <option v-for="size in [10, 15, 20, 50]" :key="size" :value="size">{{ size }} 条/页</option>
        </select>
      </div>
      <div class="hidden sm:flex sm:flex-1 sm:items-center sm:justify-end">
        <div class="mr-4">
          <p class="text-sm text-slate-400">
            显示 
            <span class="font-medium">{{ (currentPage - 1) * pageSize + 1 }}</span> 
            至 
            <span class="font-medium">{{ Math.min(currentPage * pageSize, data.length) }}</span> 
            条，共
            <span class="font-medium">{{ data.length }}</span> 条
          </p>
        </div>
        <div>
          <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
            <button 
              @click="currentPage = Math.max(1, currentPage - 1)" 
              :disabled="currentPage === 1"
              class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-slate-700 bg-slate-800 text-sm font-medium text-slate-400 hover:bg-slate-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <span class="sr-only">上一页</span>
              <i class="fas fa-chevron-left text-xs"></i>
            </button>
            
            <template v-for="page in visiblePageNumbers" :key="page">
              <button
                v-if="page !== '...'"
                @click="currentPage = page"
                :class="[
                  'relative inline-flex items-center px-4 py-2 border border-slate-700 text-sm font-medium',
                  currentPage === page 
                    ? 'bg-finance-blue-700 text-white hover:bg-finance-blue-600' 
                    : 'bg-slate-800 text-slate-300 hover:bg-slate-700'
                ]"
              >
                {{ page }}
              </button>
              <span
                v-else
                class="relative inline-flex items-center px-4 py-2 border border-slate-700 bg-slate-800 text-sm font-medium text-slate-300"
              >
                ...
              </span>
            </template>
            
            <button
              @click="currentPage = Math.min(totalPages, currentPage + 1)"
              :disabled="currentPage === totalPages"
              class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-slate-700 bg-slate-800 text-sm font-medium text-slate-400 hover:bg-slate-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <span class="sr-only">下一页</span>
              <i class="fas fa-chevron-right text-xs"></i>
            </button>
          </nav>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, computed, watch } from 'vue';

export default defineComponent({
  name: 'MarketTable',
  props: {
    data: {
      type: Array,
      required: true
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  emits: ['row-click'],
  setup(props, { emit }) {
    const columns = [
      {
        title: '#',
        dataIndex: 'rank',
        width: 'w-12',
        fixed: true
      },
      {
        title: '板块',
        dataIndex: 'regionName',
        width: 'w-24',
        fixed: true,
      },
      {
        title: '涨跌幅(%)',
        dataIndex: 'change',
        width: 'w-28',
        sorter: true
      },
      {
        title: '总成交量(万手)',
        dataIndex: 'volume',
        width: 'w-36',
        sorter: true
      },
      {
        title: '总成交额(亿元)',
        dataIndex: 'amount',
        width: 'w-36',
        sorter: true
      },
      {
        title: '净流入(亿元)',
        dataIndex: 'netflow',
        width: 'w-32',
        sorter: true
      },
      {
        title: '上涨家数',
        dataIndex: 'upCount',
        width: 'w-24',
        sorter: true
      },
      {
        title: '下跌家数',
        dataIndex: 'downCount',
        width: 'w-24',
        sorter: true
      },
      {
        title: '领涨股',
        dataIndex: 'leadingStockName',
        width: 'w-32'
      },
      {
        title: '最新价',
        dataIndex: 'latestPrice',
        width: 'w-20',
        sorter: true
      },
      {
        title: '涨跌幅(%)',
        dataIndex: 'leadingStockChange',
        width: 'w-24',
        sorter: true
      }
    ];
    const currentPage = ref(1);
    const pageSize = ref(15);
    const sortField = ref('');
    const sortOrder = ref(''); 
    const getValueByPath = (object, path) => {
      const keys = path.split('.');
      let result = object;
      
      for (const key of keys) {
        if (result && result[key] !== undefined) {
          result = result[key];
        } else {
          return undefined;
        }
      }
      
      return result;
    };
    const handleSort = (field) => {
      if (sortField.value === field) {
        if (sortOrder.value === 'asc') {
          sortOrder.value = 'desc';
        } else if (sortOrder.value === 'desc') {
          sortField.value = '';
          sortOrder.value = '';
        } else {
          sortOrder.value = 'asc';
        }
      } else {
        sortField.value = field;
        sortOrder.value = 'asc';
      }
    };
    const getSortIcon = (field) => {
      if (sortField.value !== field) {
        return 'fas fa-sort text-slate-600';
      }
      
      if (sortOrder.value === 'asc') {
        return 'fas fa-sort-up text-finance-blue-400';
      }
      
      if (sortOrder.value === 'desc') {
        return 'fas fa-sort-down text-finance-blue-400';
      }
      
      return 'fas fa-sort text-slate-600';
    };
    const sortedData = computed(() => {
      if (!sortField.value || !sortOrder.value) {
        return props.data;
      }
      
      return [...props.data].sort((a, b) => {
        let valueA, valueB;
        if (sortField.value === 'change') {
          valueA = parseFloat(a.change.value);
          valueB = parseFloat(b.change.value);
        } else if (sortField.value === 'latestPrice') {
          valueA = parseFloat(a.leadingStock.latestPrice);
          valueB = parseFloat(b.leadingStock.latestPrice);
        } else if (sortField.value === 'leadingStockChange') {
          valueA = parseFloat(a.leadingStock.change);
          valueB = parseFloat(b.leadingStock.change);
        } else {
          valueA = getValueByPath(a, sortField.value);
          valueB = getValueByPath(b, sortField.value);
          if (!isNaN(valueA)) valueA = parseFloat(valueA);
          if (!isNaN(valueB)) valueB = parseFloat(valueB);
        }
        
        if (valueA === valueB) {
          return 0;
        }
        
        const result = valueA > valueB ? 1 : -1;
        return sortOrder.value === 'asc' ? result : -result;
      });
    });
    const paginatedData = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return sortedData.value.slice(start, end);
    });
    const totalPages = computed(() => {
      return Math.ceil(props.data.length / pageSize.value);
    });
    const visiblePageNumbers = computed(() => {
      if (totalPages.value <= 7) {
        return Array.from({ length: totalPages.value }, (_, i) => i + 1);
      }
      
      let pages = [];
      pages.push(1);
      if (currentPage.value > 3) {
        pages.push('...');
      }
      let start = Math.max(2, currentPage.value - 1);
      let end = Math.min(totalPages.value - 1, currentPage.value + 1);
      if (currentPage.value <= 3) {
        end = Math.min(5, totalPages.value - 1);
      }
      if (currentPage.value >= totalPages.value - 2) {
        start = Math.max(2, totalPages.value - 4);
      }
      for (let i = start; i <= end; i++) {
        pages.push(i);
      }
      if (currentPage.value < totalPages.value - 2) {
        pages.push('...');
      }
      pages.push(totalPages.value);
      
      return pages;
    });
    watch(() => props.data, () => {
      currentPage.value = 1;
    });
    const handleRowClick = (record) => {
      emit('row-click', record);
    };
    
    return {
      columns,
      currentPage,
      pageSize,
      paginatedData,
      totalPages,
      visiblePageNumbers,
      getValueByPath,
      handleSort,
      getSortIcon,
      handleRowClick
    };
  }
});
</script>